package mylibrary.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringReader;

public class IOStreamDemo {

	public static void main(String[] args) throws Exception {
		
		//1. Read input by lines
		InputStreamReader isr = new InputStreamReader(new FileInputStream("/Study/ReadMe/Java.txt"), "GBK");
		BufferedReader in = new BufferedReader(isr);
		
//		BufferedReader in = new BufferedReader(new FileReader("/Study/ReadMe/Java.txt"));
		
		String s, s2 = new String();
		
		System.out.println(System.getProperty("file.encoding"));
		
		while ((s = in.readLine()) != null) {
			
			//System.out.println(s);
			//System.out.println(new String(s.getBytes("GBK"), "GBK"));
			
			s2 += s + "\n" ;
			PrintStream ps = new PrintStream(System.out, true, "iso8859-1");
			//ps.println(s);
		}
		in.close();
		
		//2. Input from memory
		StringReader in2 = new StringReader(s2);
		int c;
		while ((c=in2.read()) != -1) {
			//System.out.println((char)c);
		}
		
		//3. Format memory input
		DataInputStream in3 = new DataInputStream(new ByteArrayInputStream(s2.getBytes()));
//		while (true) {
//			System.out.println(in3.readChar());
//		}
		
		
		//4. File output
		BufferedReader in4 = new BufferedReader(new StringReader(s2));
		PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("c:\\test.txt")));
		int lineCount = 1;
		while((s=in4.readLine())!=null) {
			//out1.println(s);
		}
		out1.flush();
		
		
		//5. Storing & recovering data
		DataOutputStream out2 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("c:\\test1.txt")));
		out2.writeDouble(3.14159);
		out2.writeUTF("This is pi");
		out2.close();
		
		DataInputStream in5 = new DataInputStream(new BufferedInputStream(new FileInputStream("c:\\test1.txt")));				
		//System.out.println(in5.readDouble());
		//System.out.println(in5.readUTF());
		
		
		//6. Reading/writing random access files
		RandomAccessFile rf = new RandomAccessFile("c:\\rtest.dat", "rw");
		for (int i = 0; i < 10; i++) {
			rf.writeDouble(i * 1.414);			
		}
		rf.close();
		
		rf = new RandomAccessFile("c:\\rtest.dat", "rw");
		rf.seek(5 * 8);
		rf.writeDouble(47.0001);
		rf.close();
		
		rf = new RandomAccessFile("c:\\rtest.dat", "r");
		for(int i = 0; i < 10; i++) {
			System.out.println(rf.readDouble());
		}
		rf.close();
	}
}
